﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Threading.Tasks;
using BCEntity.OA.TeamWorks.TaskResourceRecord;
using Dapper;
using BCCommon;

namespace BCData.OA.TeamWorks.TaskResourceRecord
{
    public class TaskResourceRecordData: ITaskResourceRecordData
    {
        private readonly IDatabaseContext databaseContext;
        private const string QUERY = @"SELECT TaskResourceRecordId,WorkflowActivityInstanceId,TaskRecordNo,ResourceTitle,ResourceAddress,RsourceRemark,TaskStep,CreateTime FROM OA_TaskResourceRecord";
        public TaskResourceRecordData(IDatabaseContext databaseContext)
        {
            this.databaseContext=databaseContext;
        }

        public async Task<TaskResourceRecordEntity> Add(TaskResourceRecordEntity entity)
        {
            string sql = SqlCommands.GetInsertSql("OA_TaskResourceRecord", new string[] { "TaskRecordNo", "ResourceTitle", "ResourceAddress", "RsourceRemark", "TaskStep", "WorkflowActivityInstanceId" });
            sql = string.Format("{0} {1} WHERE TaskResourceRecordId=LAST_INSERT_ID()", sql, QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?TaskRecordNo", entity.TaskRecordNo, DbType.AnsiString, size: 50);
            parameters.Add("?ResourceTitle", entity.ResourceTitle, DbType.AnsiString, size: 50);
            parameters.Add("?ResourceAddress", entity.ResourceAddress, DbType.AnsiString, size: 1000);
            parameters.Add("?RsourceRemark", entity.RsourceRemark, DbType.String);
            parameters.Add("?TaskStep", entity.TaskStep, DbType.Int32,size:10);
            parameters.Add("?WorkflowActivityInstanceId", DbType.Int64, size: 20);
            return await this.databaseContext.Master.QueryFirstOrDefaultAsync<TaskResourceRecordEntity>(sql, parameters, databaseContext.Transaction);
        }
        
        public async Task<IEnumerable<TaskResourceRecordEntity>> GetList(long workflowActivityInstanceId)
        {
            string sql = string.Format(@"{0} WHERE WorkflowActivityInstanceId=?WorkflowActivityInstanceId", QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?WorkflowActivityInstanceId", workflowActivityInstanceId, DbType.Int64, size: 20);
            return await this.databaseContext.Slave.QueryAsync<TaskResourceRecordEntity>(sql, parameters);
        }
    }
}
